#include "widget.h"
#include "./ui_widget.h"

#include <QPixmap>
#include <QPalette>
#include <QDebug>
#include <QTimer>
#include <QKeyEvent>
#include <QMouseEvent>
#include <QPainter>

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
    // 加载背景图片，使用相对路径确保可移植性
    QPixmap backgroundPixmap("./images/back_ground_pic.jpeg");
    if (!backgroundPixmap.isNull()) {
        // 设置窗口大小为图片实际大小
        //this->resize(800, 600);
        //用户无法更改！
        this->setFixedSize(backgroundPixmap.width(), backgroundPixmap.height());
        // 设置背景
        QPalette palette = this->palette();
        palette.setBrush(QPalette::Window, QBrush(backgroundPixmap));
        this->setPalette(palette);
        this->setAutoFillBackground(true);
    } else {
        qDebug() << "无法加载背景图片！";
        // 加载失败时设置默认窗口大小，用户无法更改。
        this->setFixedSize(800, 600);
    }

    // 初始化游戏参数
    gameWidth = width();
    gameHeight = height();
    stepSize = 20; // 设置步长
    
    // 初始化蛇和食物
    snake = new Snake(gameWidth, gameHeight, stepSize);
    food = new Food(gameWidth, gameHeight, stepSize);
    food->generateNew(snake->body());
    
    // 加载 蛇和食物图片（新增代码）
    headUp.load("./images/on.gif");       // 原路径: "E:/MyCode/Qt_Projects/snakeat/images/on.gif"
    headDown.load("./images/down.gif");   // 原路径: "E:/MyCode/Qt_Projects/snakeat/images/down.gif"
    headLeft.load("./images/left.gif");   // 原路径: "E:/MyCode/Qt_Projects/snakeat/images/left.gif"
    headRight.load("./images/right.gif"); // 原路径: "E:/MyCode/Qt_Projects/snakeat/images/right.gif"
    body.load("./images/body.gif");       // 原路径: "E:/MyCode/Qt_Projects/snakeat/images/body.gif"
    foodImg.load("./images/food.gif");       // 原路径: "E:/MyCode/Qt_Projects/snakeat/images/food.gif"
    
    // 检查图片加载状态
    if (headUp.isNull() || headDown.isNull() || headLeft.isNull() || headRight.isNull()) {
        qDebug() << "蛇头图片加载失败！";
    }
    if (body.isNull()) qDebug() << "蛇身图片加载失败！";
    if (foodImg.isNull()) qDebug() << "食物图片加载失败！";
    
    // 设置游戏定时器
    gameTimer = new QTimer(this);
    connect(gameTimer, &QTimer::timeout, this, [=]() {
        snake->move();
        // 检测食物碰撞
        if (snake->head() == food->position()) {
            snake->grow();
            food->generateNew(snake->body());
        }
        // 检测自身碰撞
        if (snake->checkSelfCollision()) {
            snake->reset();
        }
        update(); // 触发重绘
    });
    gameTimer->start(100); // 100毫秒刷新一次
    
    // 设置窗口获得焦点（新增，可选）
    setFocusPolicy(Qt::StrongFocus);
}

Widget::~Widget()
{
    delete ui;
}

// 新增绘图事件实现
void Widget::paintEvent(QPaintEvent *event)
{
    Q_UNUSED(event);
    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing); // 抗锯齿
    
    // 绘制蛇头
    QPixmap currentHead;
    switch (snake->direction()) {
        case Snake::Up: currentHead = headUp; break;
        case Snake::Down: currentHead = headDown; break;
        case Snake::Left: currentHead = headLeft; break;
        case Snake::Right: currentHead = headRight; break;
        default: currentHead = headRight; // 默认向右
    }
    painter.drawPixmap(snake->head(), currentHead.scaled(stepSize, stepSize));
    
    // 绘制蛇身
    foreach (QPoint bodyPart, snake->body()) {
        painter.drawPixmap(bodyPart, body.scaled(stepSize, stepSize));
    }
    
    // 绘制食物
    painter.drawPixmap(food->position(), foodImg.scaled(stepSize, stepSize));
}

// 新增键盘事件处理函数
void Widget::keyPressEvent(QKeyEvent *event)
{
    // 根据按键设置蛇的移动方向（WASD控制）
    switch (event->key()) {
        case Qt::Key_W:       // W键 - 上
            snake->setDirection(Snake::Up);
            break;
        case Qt::Key_S:       // S键 - 下
            snake->setDirection(Snake::Down);
            break;
        case Qt::Key_A:       // A键 - 左
            snake->setDirection(Snake::Left);
            break;
        case Qt::Key_D:       // D键 - 右
            snake->setDirection(Snake::Right);
            break;
        default:
            // 保留默认事件处理
            QWidget::keyPressEvent(event);
    }
}
